import { createEffect, createMemo, createSignal, Index } from "solid-js";
import type { FcListContext, FcListProps } from "./types";

const FcList = <V extends any = any>(props: FcListProps<V>) => {
  const current_values = createMemo(() => {
    return (props.value ?? []) as V[];
  });

  const append = (val: V) => {
    props.onValueChanged?.([...current_values(), val]);
  };

  const appendAt = (value: V, index: number) => {
    const next_values = current_values().splice(index, 0, value);
    props.onValueChanged?.(next_values);
  };

  const removeAt = (index: number) => {
    current_values().splice(index, 1);
    props.onValueChanged?.([...current_values()]);
  };

  const clearAll = () => {
    props.onValueChanged?.([]);
  };

  const ctx = createMemo(() => {
    return {
      append,
      appendAt,
      removeAt,
      clearAll,
    } as FcListContext<V>;
  });

  createEffect(() => {
    props.onRef?.(ctx());
  });

  return (
    <Index each={current_values()}>
      {(item, index) => props.children?.(item, index, ctx())}
    </Index>
  );
};

export default FcList;
